package com.gw.redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisListUtil {
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean rPush(final String key,Object value){
        boolean result=false;
        try {
            redisTemplate.opsForList().leftPush(key,value);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 批量写入缓存
     * @param key
     * @param value
     * @return
     */
    public boolean rPushAll(final String key,Object ... value){
        boolean result=false;
        try {
            redisTemplate.opsForList().rightPushAll(key,value);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 读取缓存
     * @param key
     * @param begin
     * @param end
     * @return
     */
    public List lRange(final String key,long begin,long end){
        return redisTemplate.opsForList().range(key,begin,end);
    }

    /**
     * 通过下标读取缓存
     * @param key
     * @param index
     * @return
     */
    public Object lGetByIndex(final String key,long index){
        return redisTemplate.opsForList().index(key,index);
    }

    /**
     * 更新缓存
     * @param key
     * @param index
     * @param value
     * @return
     */
    public boolean lSet(final String key,long index,Object value){
        boolean result=false;
        try{
            redisTemplate.opsForList().set(key,index,value);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 删除缓存
     * @param key
     * @param index
     * @param value
     * @return
     */
    public boolean lRem(final String key,long index,Object value){
        boolean result=false;
        try {
            redisTemplate.opsForList().remove(key,index,value);
            result=true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
